<?php

namespace App\Admin\Forms;

use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\DB;

class ResignImportForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // 获取上传的文件路径
        $file_path = storage_path('app/public' . $input['import_file']);
        $imageFilePath =  './uploads/photo/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 0777, true);
        }

        //包含图片的Excel文件
        $objRead = IOFactory::createReader('Xlsx');
        $objSpreadsheet = $objRead->load($file_path);
        $objWorksheet = $objSpreadsheet->getSheet(0);
        $data = $objWorksheet->toArray();
        unset($data['0']);
        unset($data['1']);

        $abnormal_result = "";
        foreach($data as $k=>$v){
            $new['name']=$v['1'];
            $new['id_card']=$v['2'];
            $new['bank_deposit']=$v['3'];
            $new['bank_number']=$v['4'];
            $new['mobile']=$v['5'];
            $new['type_work']=$v['6'];
            $new['team']=$v['7'];
            $new['company']=$v['8'];
            $new['engineering']=$v['9'];

            if($new['id_card']==''){
                $abnormal_result .= '</br>[身份证未填]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

            if($new['mobile']==''){
                $abnormal_result .= '</br>[手机号未填]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

//            if($new['bank_deposit']==''){
//                $abnormal_result .= '</br>[开户行未填]:';
//                $abnormal_result .= '姓名:{'.$new['name'].'}:';
//                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
//                $abnormal_result .= '</br>';
//                continue;
//            }
//            if($new['bank_number']==''){
//                $abnormal_result .= '</br>[银行卡未填]:';
//                $abnormal_result .= '姓名:{'.$new['name'].'}:';
//                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
//                $abnormal_result .= '</br>';
//                continue;
//            }
            if($new['engineering']==''){
                $abnormal_result .= '</br>[所属工程未填]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

            $is_engineering = DB::table('engineering')->where('deleted_at',null)->where('engineering_name',$new['engineering'])->first();
            if($is_engineering == null){
                $abnormal_result .= '</br>[所属工程和系统中的名称不一致]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

            if(!preg_match("/^\d{4}-\d{2}-\d{2}$/", $v['11'])){
                $abnormal_result .= '</br>[离职日期格式错误]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

            if(!preg_match("/^1[3456789]\d{9}$/", $new['mobile'])){
                $abnormal_result .= '</br>[手机号格式不正确]:';
                $abnormal_result .= '姓名:{'.$new['name'].'}:';
                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
                $abnormal_result .= '</br>';
                continue;
            }

//            if(strlen($new['bank_number']) !== 16 && strlen($new['bank_number']) !== 19 && strlen($new['bank_number']) !== 18 && strlen($new['bank_number']) !== 17){
//                $abnormal_result .= '</br>[银行卡号格式错误]:';
//                $abnormal_result .= '姓名:{'.$new['name'].'}:';
//                $abnormal_result .= '身份证号{'.$new['id_card'].'}';
//                $abnormal_result .= '</br>';
//                continue;
//            }

        }

        if($abnormal_result != ""){
            return $this->response()->alert(true)->warning('以下人员存在异常，拒绝录入:')->detail($abnormal_result);
        }


        foreach ($objWorksheet->getDrawingCollection() as $drawing) {
            list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
            $imageFileName = $drawing->getCoordinates() . time().mt_rand(1000, 9999);
            switch ($drawing->getExtension()) {
                case 'jpg':
                case 'jpeg':
                    $imageFileName .= '.jpeg';
                    $source = imagecreatefromjpeg($drawing->getPath());
                    imagejpeg($source, $imageFilePath . $imageFileName);
                    break;
                case 'gif':
                    $imageFileName .= '.gif';
                    $source = imagecreatefromgif($drawing->getPath());
                    imagegif($source, $imageFilePath . $imageFileName);
                    break;
                case 'png':
                    $imageFileName .= '.png';
                    $source = imagecreatefrompng($drawing->getPath());
                    imagepng($source, $imageFilePath . $imageFileName);
                    break;
            }
            if($startColumn == "M"){
                $data[$startRow-1][12] = '/photo/' . $imageFileName;
            }else{
                $data[$startRow-1][13] = '/photo/' . $imageFileName;
            }

        }
//        var_dump($data);
//        die();
        $abnormal_result = "";
        foreach($data as $k=>$v){
//            var_dump($v);die();
            $new=[];
            $new['name']=$v['1'];
            $new['id_card']=$v['2'];
            $new['bank_deposit']=$v['3'];
            $new['bank_number']=$v['4'];
            $new['mobile']=$v['5'];
            $new['type_work']=$v['6'];
            $new['team']=$v['7'];
            $new['company']=$v['8'];
            $new['engineering']=$v['9'];
            if($v['10'] == null){
                $new['enter_time']=Carbon::now();
            }else{
                $new['enter_time']=$v['10'];
            }
            if($v['11'] == null){
                $new['exit_time']=Carbon::now();
            }else{
                $new['exit_time']=$v['11'];
            }
            $new['photo_portrait']=$v['12'];
            $new['photo_emblem']=$v['13'];
            $new['age']=$this->getAgeByID($new['id_card']);
            $new['status']=2;
            $new['enter_date']=Carbon::now()->format('Y-m');
            $new['exit_date']=Carbon::now()->format('Y-m');
            $new['uploader'] = Admin::user()->id;

            //该人员是否已经存在
            $is_exist = DB::table('work_user')->where('deleted_at',null)->where('id_card',$v['2'])->first();
            if($is_exist == null){
                DB::table('work_user')->insert($new);
                $history = [];
                $history['name'] = $new['name'];
                $history['id_card'] = $new['id_card'];
                $history['engineering'] = $new['engineering'];
                $history['type'] = 1;
                $history['details'] = '首次入职';
                $history['enter_time'] = $new['enter_time'];
                $history['created_at'] = Carbon::now();
                DB::table('work_user_history')->insert($history);

                $history = [];
                $history['name'] = $new['name'];
                $history['id_card'] = $new['id_card'];
                $history['engineering'] = $new['engineering'];
                $history['type'] = 2;
                $history['details'] = '离职';
                $history['exit_time'] = $new['exit_time'];
                $history['created_at'] = Carbon::now();
                DB::table('work_user_history')->insert($history);

            }else{
                //记录未离职人员
                if($is_exist->engineering != $new['engineering'] && $is_exist->status == 1){
                    $abnormal_result .= '</br>[未离职]:';
                    $abnormal_result .= '过去所在工地{'.$is_exist->engineering.'}:';
                    $abnormal_result .= '姓名:{'.$is_exist->name.'}:';
                    $abnormal_result .= '身份证号{'.$is_exist->id_card.'}';
                    $abnormal_result .= '</br>';
                    continue;
                }
                //记录不端行为人员
                if($is_exist->misdeed != 1){
                    $abnormal_result .= '</br>[劣迹]:';
                    $abnormal_result .= '劣迹发生工地{'.$is_exist->engineering.'}:';
                    $abnormal_result .= '姓名:{'.$is_exist->name.'}:';
                    $abnormal_result .= '身份证号{'.$is_exist->id_card.'}';
                    $abnormal_result .= '</br>';
                    continue;
                }

                if($is_exist->status == 1){
                    $history = [];
                    $history['name'] = $new['name'];
                    $history['id_card'] = $new['id_card'];
                    $history['engineering'] = $new['engineering'];
                    $history['type'] = 2;
                    $history['details'] = '离职';
                    $history['exit_time'] = $new['exit_time'];
                    $history['created_at'] = Carbon::now();
                    DB::table('work_user_history')->insert($history);
                }

                //删除旧图片
//                if(!empty($is_exist->photo_portrait) && $is_exist->photo_portrait != '#NAME?'){
//                    unlink(public_path().'/uploads'.$is_exist->photo_portrait);
//                }
//                if(!empty($is_exist->photo_emblem) && $is_exist->photo_emblem != '#NAME?'){
//                    unlink(public_path().'/uploads'.$is_exist->photo_emblem);
//                }
                DB::table('work_user')->where('id_card',$v['2'])->update($new);
                if($is_exist->status == 2){
                    $history = [];
                    $history['name'] = $new['name'];
                    $history['exit_time'] = $new['exit_time'];
                    $history['created_at'] = Carbon::now();
                    DB::table('work_user_history')->where('id_card',$new['id_card'])->where('type',2)->update($history);
                }
            }

            DB::table('company')->updateOrInsert(['name'=>$v['8']],['name'=>$v['8'],'created_at'=>Carbon::now()]);
            DB::table('team')->updateOrInsert(['name'=>$v['7']],['name'=>$v['7'],'created_at'=>Carbon::now()]);
            DB::table('engineering')->updateOrInsert(['engineering_name'=>$v['9']],['engineering_name'=>$v['9'],'created_at'=>Carbon::now()]);
        }

        if($abnormal_result == ""){
            return $this->response()->success('ok')->refresh();
        }
        return $this->response()->alert(true)->warning('以下人员存在异常，拒绝录入:')->detail($abnormal_result);
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        // 禁用重置表单按钮
        $this->disableResetButton();

        // 文件上传
        $this->file('import_file', ' ')
            ->disk('public')
            ->accept('xlsx')
            ->uniqueName()
            ->autoUpload()
            ->move('/import')
            ->maxSize(1024000)
            ->help('支持xlsx');
    }

    public function getAgeByID($id){
        //过了这年的生日才算多了1周岁
        if(empty($id)) return '';
        $date=strtotime(substr($id,6,8));
        //获得出生年月日的时间戳
        $today=strtotime('today');
        //获得今日的时间戳
        $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数
        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
        return $age;
    }
}
